﻿using System;
using System.Windows.Forms;

namespace UpwardsTimeClock.Prototype
{
    public partial class CountdownControl : UserControl
    {
        public CountdownControl()
        {
            InitializeComponent();
        }

        private TimeSpan _remainingTimeSpan;
        private DateTime _endTime;

        public TimeSpan RemainingTimeSpan
        {
            set
            {
                _remainingTimeSpan = value - new TimeSpan(0,0,0,0,value.Milliseconds);
            }
            get
            {
                _remainingTimeSpan = _endTime - DateTime.Now;
                if (_remainingTimeSpan.TotalMilliseconds < 0)
                    _remainingTimeSpan = TimeSpan.Zero;
                return _remainingTimeSpan;
            }
        }

        public void Start()
        {
            _endTime = DateTime.Now + _remainingTimeSpan;
            CountdownTimer.Enabled = true;
        }

        public void Stop()
        {
            CountdownTimer.Enabled = false;
        }

        private void CountdownTimer_Tick(object sender, EventArgs e)
        {
            TimeSpan remainingTimeSpan = RemainingTimeSpan;
            CountdownLabel.Text =
                string.Format("{0:00}:{1:00}:{2:000}",
                remainingTimeSpan.Minutes,
                remainingTimeSpan.Seconds,
                remainingTimeSpan.Milliseconds);
            CountdownLabel.Refresh();
            if (remainingTimeSpan == TimeSpan.Zero)
            {
                Stop();
            }
        }
    }
}
